using System;
using EnvDTE;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using EnvDTE80;

namespace TeamReview.Replay
{
	internal sealed class FirstSnippetInDocumentLink : ReplayLink
	{
	    public FirstSnippetInDocumentLink(DTE2 applicationObject) : base(applicationObject)
	    {
	    }

	    public override ReplayReceipt TryShowReplay(WorkItem workItem, DTE2 applicationObject)
        {
            ReplayReceipt receipt = new ReplayReceipt();

            string fileName = AbsoluteCodeFilePath(workItem);
            object snippetObject = workItem.Fields[Constants.CODE_SNIPPET_FIELD].Value;

            if (String.IsNullOrEmpty(fileName) || !System.IO.File.Exists(fileName) || snippetObject == null)
                return receipt;

            string snippet = snippetObject.ToString();

            EnvDTE.Document document = applicationObject.Documents.Open(fileName, "Auto", false);
            if (document == null)
                return receipt;

            EnvDTE.TextDocument td = (EnvDTE.TextDocument) document.Object("");

            if (td == null || td.Selection == null)
                return receipt;

            receipt.Selection = td.Selection;
            receipt.Selection.GotoLine(td.StartPoint.Line, false);
            EnvDTE.EditPoint startPoint = td.CreateEditPoint(receipt.Selection.ActivePoint);
            receipt.Selection.GotoLine(td.EndPoint.Line, true);
            EnvDTE.EditPoint endPoint = td.CreateEditPoint(receipt.Selection.ActivePoint);
            receipt.Selection.MoveToPoint(startPoint, false);
            receipt.Selection.MoveToPoint(endPoint, true);

            FindCodeSnippet(receipt, snippet,
                            String.Format(
                                "First occurrence of code snippet found in the document. Exact code not found at original line numbers."));
            HighlightCodeSnippet(receipt);

            return receipt;
        }
	}
}
